#!/bin/bash

function setup_dhcrelay_for_cobbler {
  VERSION=$(awk '/release/{gsub(/"/, "");print $2}' /etc/fuel/version.yaml)
  container="fuel-core-${VERSION}-cobbler"
  cobbler_ip=$(docker  inspect --format='{{.NetworkSettings.IPAddress}}' $container)
  admin_interface=$(grep interface: /etc/fuel/astute.yaml | cut -d':' -f2 | tr -d ' ')
  cat > /etc/sysconfig/dhcrelay << EOF
# Command line options here
DHCRELAYARGS=""
# DHCPv4 only
INTERFACES="$admin_interface docker0"
# DHCPv4 only
DHCPSERVERS="$cobbler_ip"
EOF
  rpm -q dhcp 2>&1 > /dev/null || yum --quiet -y install dhcp
  chkconfig dhcrelay on
  service dhcrelay restart
}

if ! grep -q docker0 /proc/net/dev; then
  sleep 10
fi

setup_dhcrelay_for_cobbler

( ps -p "`cat /var/run/dhcrelay.pid 2>/dev/null`" &>/dev/null || /etc/init.d/dhcrelay start )
if [ $? -eq 0 ]; then
  pid=$(cat /var/run/dhcrelay.pid)
  while test -d "/proc/$pid/fd"; do
    sleep 30
  done
fi
